<template>
  <div>
    <el-table
      ref="refTable"
      v-loading="isFetching"
      :data="tableData"
      element-loading-text="Loading"
      fit
      style="width: 100%">
      <el-table-column fixed type="expand">
        <template slot-scope="{ row }">
          <el-form
            :ref="`diagnose6a_form${row.__fid}`"
            :model="row"
            :rules="rules"
            label-position="right"
            label-width="150px"
            size="small"
            class="table_expand">
            <div style="width: 90%; display: flex; flex-direction: row; justify-content: flex-start; gap: 50px">
              <div>
                <el-form-item label="活动月份" prop="activityMonth">
                  <el-date-picker
                    v-model="row.activityMonth"
                    type="month"
                    placeholder="选择月份"
                    :disabled="row.id && row.id > 0"
                    :picker-options="{ disabledDate: picDisabledDate }"
                    format="yyyy-MM"
                    value-format="yyyy-MM"
                    style="width: 180px"></el-date-picker>
                </el-form-item>
                <el-form-item label="活动名称" prop="activityName">
                  <el-input
                    v-model="row.activityName"
                    :disabled="row.id && row.id > 0"
                    type="textarea"
                    maxlength="64"
                    show-word-limit
                    placeholder="请输入活动名称"
                    style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="活动类型" prop="activityType">
                  <el-select v-model="row.activityType" placeholder="请选择活动类型" style="width: 180px">
                    <el-option
                      v-for="item in EnumActivityType"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="邀请范围" prop="invitationScope">
                  <el-select v-model="row.invitationScope" placeholder="请选择邀请范围" style="width: 180px">
                    <el-option
                      v-for="item in EnumInvitationScope"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="邀请成功率" prop="invitationSuccessRate">
                  <el-input-number
                    v-model="row.invitationSuccessRate"
                    :min="0"
                    :max="100"
                    :step="0.01"
                    :precision="2"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <!--操作-->
                <el-form-item>
                  <el-button v-if="isUpdating" type="primary" disabled icon="el-icon-loading" style="width: 120px">
                    提交中
                  </el-button>
                  <el-button
                    v-else-if="row.id === undefined"
                    type="primary"
                    @click="handleSubmitForm(`diagnose6a_form${row.__fid}`, true, row)">
                    保存
                  </el-button>
                  <el-button v-else type="warning" @click="handleSubmitForm(`diagnose6a_form${row.__fid}`, false, row)">
                    修改
                  </el-button>
                </el-form-item>
              </div>
              <div>
                <el-form-item label="参与人数" prop="participantsCount">
                  <el-input-number
                    v-model="row.participantsCount"
                    :min="0"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="主要产品" prop="mainProduct">
                  <el-input
                    v-model="row.mainProduct"
                    type="textarea"
                    maxlength="128"
                    placeholder="请输入主要产品"
                    show-word-limit
                    style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="成交金额" prop="transactionAmount">
                  <el-input-number
                    v-model="row.transactionAmount"
                    :min="0"
                    :step="0.01"
                    :precision="2"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="成交率(%)" prop="transactionRate">
                  <el-input-number
                    v-model="row.transactionRate"
                    :min="0"
                    :max="100"
                    :step="0.01"
                    :precision="2"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="是否达到预期" prop="metExpectations">
                  <el-switch v-model="row.metExpectations" active-text="是" inactive-text="否"></el-switch>
                </el-form-item>
                <el-form-item label="信息来源">
                  <el-input
                    v-model="row.infoSource"
                    type="textarea"
                    maxlength="128"
                    show-word-limit
                    style="width: 180px"></el-input>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column fixed prop="activityMonth" label="活动月份" align="center" width="80"></el-table-column>
      <el-table-column
        prop="activityName"
        label="活动名称"
        align="center"
        width="120"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="activityType" label="活动类型" align="center" width="100">
        <template slot-scope="{ row }">
          {{ row.activityType | fltActivityType }}
        </template>
      </el-table-column>
      <el-table-column prop="invitationScope" label="邀请范围" align="center" width="110">
        <template slot-scope="{ row }">
          {{ row.invitationScope | fltInvitationScope }}
        </template>
      </el-table-column>
      <el-table-column prop="invitationSuccessRate" label="邀请成功率" align="center" width="100"></el-table-column>
      <el-table-column prop="participantsCount" label="参与人数" align="center" width="80"></el-table-column>
      <el-table-column
        prop="mainProduct"
        label="主要产品"
        align="center"
        width="120"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="transactionAmount" label="成交金额" align="center" width="100"></el-table-column>
      <el-table-column prop="transactionRate" label="成交率(%)" align="center" width="100"></el-table-column>
      <el-table-column prop="metExpectations" label="达到预期" align="center" width="80">
        <template slot-scope="{ row }">
          {{ row.metExpectations ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="创建日期" align="center" width="120">
        <template slot-scope="{ row }">{{ row.createDate ? row.createDate.substring(0, 11) : '--' }}</template>
      </el-table-column>
      <el-table-column fixed="right" align="center" width="120">
        <template slot="header">
          <el-button type="primary" size="mini" plain @click.stop="handleAddEmptyRow">添加一行</el-button>
        </template>
        <template slot-scope="{ row }">
          <el-button v-if="row.id && row.id > 0" type="danger" size="mini" plain @click.stop="handleDelete(row)">
            删除
          </el-button>
          <el-button v-else type="warning" size="mini" plain @click.stop="handleDeleteRow(row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { delOpaADiagnoseById, getOpaADiagnoseByNo, saveOpaADiagnoseByNo } from '@/api/diagnose';
// 引入自定义组件
import '@/utils/datefmt';
// 引入第三方组件
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

const EmptyOpaAData = {
  activityMonth: undefined, // NOT NULL
  activityName: '', // NOT NULL
  activityType: 1, // NOT NULL
  activityId: null,
  invitationScope: undefined, // NOT NULL
  invitationSuccessRate: 0.0, // NOT NULL
  participantsCount: 0,
  mainProduct: '',
  transactionAmount: 0.0,
  transactionRate: 0.0, // NOT NULL
  metExpectations: false, // NOT NULL
  infoSource: null,
  coachId: null,
  coachName: null,
  createDate: null,
  __fid: '', // Form 表单ID
};

const EnumActivityType = [
  { code: 1, name: '业绩类活动' },
  { code: 2, name: '客情类活动' },
];
const EnumInvitationScope = [
  { code: 1, name: '精选部分顾客' },
  { code: 2, name: '大部分A客' },
  { code: 3, name: '大部分A+B客' },
  { code: 4, name: '大部分A+B+C客' },
];

export default {
  name: 'Diagnose6a',
  filters: {
    fltActivityType(val) {
      const tmp = EnumActivityType.find(x => x.code == val);
      if (tmp) {
        return tmp.name;
      }
      return '';
    },
    fltInvitationScope(val) {
      const tmp = EnumInvitationScope.find(x => x.code == val);
      if (tmp) {
        return tmp.name;
      }
      return '';
    },
  },
  data() {
    return {
      tableData: [],
      salon: {},
      rules: {
        activityMonth: [{ required: true, message: '活动月份不能为空', trigger: 'blur' }],
        activityName: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
        activityType: [{ required: true, message: '活动类型不能为空', trigger: 'blur' }],
        invitationScope: [{ required: true, message: '邀请范围不能为空', trigger: 'blur' }],
        invitationSuccessRate: [{ required: true, type: 'number', message: '邀请成功率不能为空', trigger: 'blur' }],
        transactionRate: [{ required: true, type: 'number', message: '成交率不能为空', trigger: 'blur' }],
        metExpectations: [{ required: true, type: 'boolean', message: '是否达到预期不能为空', trigger: 'blur' }],
      },
      EnumActivityType: EnumActivityType,
      EnumInvitationScope: EnumInvitationScope,
      isFetching: false, // 通用的&互斥的, 加载后端数据
      isUpdating: false,
    };
  },
  computed: {
    ...mapGetters(['deptId', 'openId', 'id', 'name']),
  },
  created() {},
  methods: {
    loadDiagnoseData: async function (salon /* {salonId: '', salonNo: '', salonName: '', diagnoseNo: ''} */) {
      if (!salon || !salon.diagnoseNo) {
        return;
      }
      this.salon = Object.assign({}, salon);
      this.loadDiagnose6a();
    },
    loadDiagnose6a: async function () {
      if (this.isFetching) {
        return;
      }
      this.isFetching = true;
      this.tableData.splice(0, this.tableData.length);
      const errAlertMsg = '查询A活动复盘信息失败';
      await getOpaADiagnoseByNo(this.salon.diagnoseNo)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret && ret.length > 0) {
            ret.forEach(x => {
              x.__fid = this.getRadomStr6();
              this.tableData.push(x);
            });
          }
        })
        .catch(err => {
          console.log('getOpaADiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isFetching = false;
        });
    },
    handleAddEmptyRow: async function () {
      const cpy = Object.assign({}, EmptyOpaAData);
      cpy.coachName = this.name;
      cpy.__fid = this.getRadomStr6();
      this.tableData.push(cpy);
    },
    handleDelete: async function (row) {
      const errAlertMsg = '删除A活动复盘信息失败';
      delOpaADiagnoseById(row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.handleDeleteRow(row);
        })
        .catch(err => {
          console.log('delOpaADiagnoseById', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    handleDeleteRow: async function (row) {
      // 根据 index 从 this.tableData 中将数据删除
      const index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.tableData.splice(index, 1);
      }
    },
    picDisabledDate(date) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return !(date - today < 0);
    },
    getRadomStr6() {
      // 生成长度为 6 的随机字符串
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 6; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },
    handleSubmitForm: async function (formName, isadd, row) {
      // Validate row data against rules
      for (const key in this.rules) {
        if (this.rules.hasOwnProperty(key)) {
          const rule = this.rules[key][0];
          if (rule.required && (row[key] === undefined || row[key] === null)) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'array' && row[key].length < rule.min) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'number' && typeof row[key] !== 'number') {
            MessageBox.alert(rule.message);
            return;
          }
        }
      }

      if (row.id <= 0) {
        row.id = null;
      }

      this.isUpdating = true;
      const errAlertMsg = '保存A活动复盘信息失败';
      saveOpaADiagnoseByNo(this.salon.diagnoseNo, row)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadDiagnose6a();
          MessageBox.alert('保存成功');
        })
        .catch(err => {
          console.log('saveOpaADiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.table_expand {
  padding: 5px 16px;
  font-size: 0;
  background-color: rgb(249, 243, 234);

  .star_level {
    width: 180px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    gap: 10px;
  }
}
.table_expand label {
  width: 90px;
  color: #99a9bf;
}
.table_expand .el-form-item {
  margin-right: 0;
  margin-bottom: 5px;
  width: 50%;
}

.facial_model {
  width: 40vw;
  height: 100vh;
  position: fixed;
  top: 0;
  right: 1vw;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
}
</style>
